package com.flx.noodle.websocket.dao.impl;

import com.flx.noodle.websocket.dao.UserDao;
import com.flx.noodle.websocket.dao.mapper.UserRowMapper;
import com.flx.noodle.websocket.entity.SSOUser;
import com.flx.noodle.websocket.searcher.UserSearcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by fenglixiong on 2017/10/2.
 */
@Repository
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {


    @Autowired
    UserDaoImpl(@Qualifier("dataSource") DataSource dataSource){
        setDataSource(dataSource);
    }

    public SSOUser getUserById(int id) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "select * from ws_user where id = ?";
        List<SSOUser> userList = _jdbc.query(sql,new Object[]{id},new UserRowMapper());
        return userList.size()>0?userList.get(0):null;
    }

    public SSOUser getUserByName(String userName){
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "select * from ws_user where user_name = ?";
        List<SSOUser> userList = _jdbc.query(sql,new Object[]{userName},new UserRowMapper());
        return userList.size()>0?userList.get(0):null;
    }

    public int insertUser(final SSOUser ssoUser) {

        JdbcTemplate _jdbc = this.getJdbcTemplate();
        final String sql = "insert into ws_user (user_name,pass_word,info) values (?,?,?)";
        int ret = _jdbc.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1,ssoUser.getUserName());
                ps.setString(2,ssoUser.getPassWord());
                ps.setString(3,ssoUser.getInfo());
                return ps;
            }
        });
        return ret;
    }

    public int updateUser(final SSOUser ssoUser) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        final String sql = "update ws_user set user_name=?,pass_word=?,info=? where id = ? ";
        int ret = _jdbc.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1,ssoUser.getUserName());
                ps.setString(2,ssoUser.getPassWord());
                ps.setString(3,ssoUser.getInfo());
                ps.setInt(4,ssoUser.getUserId());
                return ps;
            }
        });
        return ret;
    }

    public int deleteUser(int id) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "delete from ws_user where id = ?";
        int ret = _jdbc.update(sql,new Object[]{id});
        return ret;
    }

    public List<SSOUser> findUserList(UserSearcher searcher) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        List<Object> params = new ArrayList<Object>();
        String sql = "select * from ws_user where 1 = 1 ";
        if(searcher.getUserId()!=null){
            sql += "and id = ? ";
            params.add(searcher.getUserId());
        }
        if(searcher.getUserName()!=null){
            sql += "and user_name like ? ";
            params.add("%"+searcher.getUserName()+"%");
        }
        String sql_count = "select count(*) from ("+sql+") s";
        int rowCount = _jdbc.queryForObject(sql_count,params.toArray(),Integer.class);
        searcher.setTotalResults(rowCount);
        sql += " order by id desc";
        //分页
        sql += " limit ? , ? ";
        params.add((searcher.getPage() - 1) * searcher.getPageSize());
        params.add(searcher.getPageSize());

        return _jdbc.query(sql,params.toArray(),new UserRowMapper());
    }

    public SSOUser getUserBySessionId(String sessionId) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "select * from ws_user where session_id = ?";
        List<SSOUser> userList = _jdbc.query(sql,new Object[]{sessionId},new UserRowMapper());
        return userList.size()>0?userList.get(0):null;
    }

    public int updateUserSessionId(int userId, String sessionId) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "update ws_user set session_id = ? where id= ?";
        return _jdbc.update(sql,new Object[]{sessionId,userId});
    }
}
